package com.heima;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.pojo.Article;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.mapper.ArticleContentMapper;
import com.heima.mapper.ArticleMapper;
import com.heima.article.pojo.ArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

@SpringBootTest(classes = ArticleApplication.class)
@RunWith(SpringRunner.class)
public class upLoad2MinioHtml {

    @Autowired
    private ArticleContentMapper contentMapper;

    @Autowired
    private ArticleMapper articleMapper;

    //Freemarker模板引擎
    @Autowired
    private Configuration configuration;

    //用于上传文件至minio
    @Autowired
    private MinIOFileStorageService minioService;

    /**
     * 通过Freemarker生成html，再上传至minio。得到访问的路径
     */
    @Test
    public void testArticle() throws Exception {
        //1.查询文章内容
        LambdaQueryWrapper<ArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleContent::getId, 1383827787742498817L);
        //得到文章内容
        ArticleContent articleContent = contentMapper.selectOne(queryWrapper);

        if (StringUtils.isNotBlank(articleContent.getContent())) {
            //2.生成html
            //freemarker的模板对象，获取模板
            Template template = configuration.getTemplate("article.ftl");

            //先对数据模型处理
            HashMap<String, Object> map = new HashMap<>();
            //放进map中，注意key为content，将content文章由字符串转为对象，因为模板文件遍历时按照对象来遍历的
            map.put("content", JSONArray.parseArray(articleContent.getContent()));

            //创建一个输出流
            StringWriter out = new StringWriter();

            //合成，第一个参数 数据模型，第二个参数  输出流
            template.process(map, out);

            //3.上传至minio
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = minioService.uploadHtmlFile("", articleContent.getArticleId() + "html", in);

            //4.修改ap_article表的static_url字段为minio的路径
            Long articleId = articleContent.getArticleId();
            LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Article::getStaticUrl, path);
            updateWrapper.eq(Article::getId, articleId);
            int update = articleMapper.update(null, updateWrapper);
            System.out.println(update);
        }

    }

}
